package com.system.manager.modules.assit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.manager.common.entity.PageDTO;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.assit.entity.AssExpert;
import com.system.manager.modules.assit.entity.ProjectExpert;
import com.system.manager.modules.assit.enums.AssitErrorCode;
import com.system.manager.modules.assit.exception.AssitException;
import com.system.manager.modules.assit.mapper.AssExpertMapper;
import com.system.manager.modules.assit.mapper.ProjectExpertMapper;
import com.system.manager.modules.assit.service.IAssExpertService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.manager.modules.authorized.entity.User;
import com.system.manager.modules.authorized.enums.SubjectType;
import com.system.manager.modules.authorized.service.IUserService;
import com.system.manager.modules.projectLibrary.entity.Project;
import com.system.manager.modules.projectLibrary.mapper.ProjectMapper;
import com.system.manager.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxp
 * @since 2021-11-20
 */
@Slf4j
@Transactional
@Service
public class AssExpertServiceImpl extends ServiceImpl<AssExpertMapper, AssExpert> implements IAssExpertService {

    private Integer autoNum = 1006;
    private String PREFIX = "zj";

    public Integer getCurrNum(){
        return autoNum;
    }

    public String getPrefix(){
        return PREFIX;
    }

    public Integer autoIncrement(){
        this.autoNum = autoNum + 1;
        return getCurrNum();
    }

    // 获取角色证号
    public synchronized String getAutoAccount(){
        return PREFIX + autoIncrement();
    }

    @Autowired
    private AssExpertMapper expertMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ProjectExpertMapper projectExpertMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Override
    public AssExpert register(AssExpert expert) {

        // 1.根据电话号码查询
        QueryWrapper<AssExpert> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", expert.getPhone());
        AssExpert expert1 = baseMapper.selectOne(wrapper);

        // 2.判断当前的专家是否已经提交过申请
        if(expert1 != null){
            if(expert1.getStatus() == 0 || expert1.getStatus() == 1){
                throw new AssitException(AssitErrorCode.EXPERT_IS_EXISTS);
            }else{
                throw new AssitException(AssitErrorCode.EXPERT_IS_REFUSE);
            }
        }

        try {
            baseMapper.insert(expert);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException();
        }

        return expert;
    }

    @Override
    public PageDTO<AssExpert> selectLists(Integer page, Integer size, Integer type, String account, String phone, String expertname, String tchArea, Integer status) {
        Page<AssExpert> userPage = new Page<>(page, size);

        // 1.根据条件查询出当前所有的对象，并进行分页封装
        List<AssExpert> userList = new ArrayList<>();
        try {
            userList = expertMapper.selectCondition(userPage, type, account, expertname, phone, tchArea, status);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException();
        }

        // 2.将查询出来的数据返回给前端
        PageDTO<AssExpert> userPageDTO = new PageDTO<>();
        userPageDTO.setData(userList);
        userPageDTO.setCount(userPage.getTotal());
        return userPageDTO;

    }

    /**
     * 增加新用户
     * @param assExpert
     * @return
     */
    @Override
    public AssExpert insert(AssExpert assExpert) {
        // 1.根据角色生成角色对应的自增帐号
        String autoAccount = getAutoAccount();
        log.info("----->当前的证号" + autoAccount);
        assExpert.setAccount(autoAccount);

        try {
            // 2.插入到user表中
            User user = new User();
            user.setUserAccount(autoAccount);
            user.setRole(SubjectType.EXPERT.getType());
            user.setName(assExpert.getExpertname());
            user.setPhone(assExpert.getPhone());
            log.info("---->插入用户表");
            User newUser = userService.insert(user);

            // 3.插入到专家表
            // 3.1 手动添加不需要申请
            assExpert.setStatus(1);
            assExpert.setUserId(newUser.getUserId());
            log.info("----->插入专家表");
            saveOrUpdate(assExpert);

        } catch (BeansException e) {
            e.printStackTrace();
            throw new SysException();
        }

        return assExpert;
    }

    @Override
    public boolean agree(Integer expertId) {
        // 1.获取当前专家的信息
        AssExpert assExpert = getById(expertId);

        // 2.判断是否为空
        if(assExpert == null){
            throw new AssitException(AssitErrorCode.USER_NOT_EXISTS);
        }

        // 3.生成专家证号
        String autoAccount = getAutoAccount();
        assExpert.setAccount(autoAccount);

        // 4.插入到user表中
        AssExpert newExpert = insert(assExpert);

        // 5.发送邮件
        // 5.1设置邮件主题内容
        String content = "【注册成功通知】：<br/>" +
                newExpert.getExpertname()+ "先生/女士：<br/>" +
                "  您于" + newExpert.getUpdateTime() +"在" + "<a href='http://www.yxpss.top/school/'>【专项资金系统】</a>" +
                "中通过了申请，以下是您的证号信息，请登陆之后及时修改您的密码：<br/>" +
                "证号：" + newExpert.getAccount()  + "<br/>" +
                "密码：111111<br/>" +
                "<strong>感谢您的申请！祝您生活愉快</strong>";
        MailUtils.sendMail(newExpert.getEmail(), content, "【专项资金系统】注册成功通知");

        return true;
    }

    @Override
    public boolean disagree(Integer expertId) {
        // 1.获取当前专家的信息
        AssExpert assExpert = getById(expertId);

        // 2.判断是否为空
        if(assExpert == null){
            throw new AssitException(AssitErrorCode.USER_NOT_EXISTS);
        }

        // 3.设置当前的状态为退回
        assExpert.setStatus(2);

        updateById(assExpert);

        // 5.发送邮件
        // 5.1设置邮件主题内容
        String content = "【注册成功通知】：<br/>" +
                assExpert.getExpertname()+ "先生/女士：<br/>" +
                "  您于" + assExpert.getCreateTime() +"在" + "<a href='http://www.yxpss.top/school/'>【专项资金系统】</a>" +
                "中提交的申请未通过，我们质疑了您的专业技能，请您自我反思一下。<br/>" +
                "<strong>感谢您的申请！祝您生活愉快</strong>";

        MailUtils.sendMail(assExpert.getEmail(), content, "【专项资金系统】注册成功通知");

        return true;
    }
    

    /**
     * 项目授派专家
     */
    @Override
    public void postProjectExpert(List<Integer> menusId, Integer id) {
        //插入到项目专家中间表中
        for (Integer expertId : menusId) {
            ProjectExpert projectExpert = new ProjectExpert();
            projectExpert.setProjectId(id);
            projectExpert.setExpertId(expertId);
            projectExpert.setStatus(0);

            projectExpertMapper.insert(projectExpert);
        }

        //修改项目状态
        Project project = new Project();
        project.setId(id);
        project.setCheckAccept(2);

        projectMapper.updateById(project);
    }

}
